#include <stdio.h>
#include "ofc/DXML.h"
#include "ofc/DFile.h"

int main(int argc, char *argv[])
{
#ifdef HAVE_DXML 
  DXMLTree      *tree  = [DXMLTree new];
  DFile         *file  = [DFile    new];
  DTreeIterator *iter  = [DTreeIterator alloc];
  DXMLNode      *node;

  char           name1[] = "example.xml";
  char           name2[] = "exampl2.xml";

  if ([file open :name1 :"r"])         // Open the xml file for reading
  {
    if ([tree read :file :name1 :'|']) // Read the file into the tree
    {
      printf("File \"%s\" succesfully read in XML tree.\n", name1);

      [file close];

      printf("XML-nodes in tree:%ld\n", [tree length]);

      [iter init :tree];               // Use the tree
      
      node = [iter root];
      while (node != nil)
      {
        switch ([node type])           // Print node info
        {
          case DXML_ELEMENT     : printf("Element:%s\n", [node name]); break;
          case DXML_ATTRIBUTE   : printf("Attribute:%s - %s\n", [node name], [node value]); break;
          case DXML_TEXT        : printf("Text:%s\n", [node value]); break;
          case DXML_CDATA       : printf("CDATA:%s\n", [node value]); break;
          case DXML_ENTITY_REF  : break;
          case DXML_ENTITY      : break;
          case DXML_PI          : break;
          case DXML_COMMENT     : printf("Comment:%s\n", [node value]); break;
          case DXML_DOCUMENT    : printf("Document:%s\n", [node value]); break;
          case DXML_DOC_TYPE    : break;
          case DXML_DOC_FRAGMENT: break;
          case DXML_NOTATION    : break;
          case DXML_NAMESPACE   : break;
        }

        if ([iter hasChildren])        // Move to the next node
        {
          node = [iter child];
        }
        else if ([iter isLast])
        {
          node = [iter parent];
          if (node != nil) 
            node = [iter next];
        }
        else
        {
          node = [iter next];
        }
      }
      
      if ([file open :name2 :"w"])     // Open the destination file for writing
      {
        if ([tree write :file :name2]) // Write the tree to the file
          printf("Xml tree succesfully written to \"%s\".\n", name2);
        else
          printf("Could not write the xml tree file \"%s\".\n", name2);

        [file close];
      }
      else
        printf("Could not open \"%s\" for writing:%d\n", name2, [file error]);
    }
    else
    {
      printf("Could not read the xml file.\n");
      [file close];
    }
  }
  else
    printf("Could not open \"%s\":%d\n", name1, [file error]);

  [tree free];                         // Cleanup
  [file free];
  [iter free];
#else
  printf("DXML is not present in the library.\n");
#endif
  return 0;
}


